package cn.bytecollege.admin.controller;

import cn.bytecollege.admin.service.AdminService;
import cn.bytecollege.common.constant.Resource;
import cn.bytecollege.common.entity.Admin;
import cn.bytecollege.common.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "SuperLoginController",value = "/super/login")
public class SuperLoginController extends HttpServlet {
    private AdminService adminService = null;
    public SuperLoginController(){
        adminService = new AdminService();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       request.getRequestDispatcher("/super/superLogin.jsp").forward(request,response);

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String msg = null;
        // 1、接收请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 2、调用Service方法
        Admin admin = adminService.findByUsername(username);
        // 3、对比用户名密码是否正确
        if(admin==null){
            msg = "管理员账号不存在";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("/super/superLogin.jsp").forward(request,response);
            return;
        }
        if(username.equals(admin.getAdminName())&& MD5Util.md5Encode(password).equals(admin.getAdminPassword())){
            //session中封装用户信息
            HttpSession session = request.getSession();
            session.setAttribute("admin",admin);
            response.sendRedirect("/super/index.jsp");
        }else{
            msg = "管理员账号或密码错误！";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher("/super/superLogin.jsp").forward(request,response);
        }
    }

}

